package top.hzy520.personalblog.service;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import top.hzy520.personalblog.NotFoundException;
import top.hzy520.personalblog.dao.TagsRepository;
import top.hzy520.personalblog.po.Tag;

import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.List;

@Service
public class TagServiceImpl implements TagService {
    @Autowired
    private TagsRepository tagsRepository;
    @Transactional
    @Override
    public Tag saveTag(Tag tag) {
        return tagsRepository.save(tag);
    }
    @Transactional
    @Override
    public Tag getTag(Long id) {
        return tagsRepository.findOne(id);
    }
    @Transactional
    @Override
    public Page<Tag> listTag(Pageable pageable) {
        return tagsRepository.findAll(pageable);
    }

    @Override
    public List<Tag> listtag() {
        return tagsRepository.findAll();
    }

    @Override
    public List<Tag> listTag(Integer size) {
        Sort sort=new Sort(Sort.Direction.DESC,"blogs.size");
        Pageable pageable=new PageRequest(0,size,sort);
        return tagsRepository.findTop(pageable);
    }

    @Transactional
    @Override
    public Tag getTagByName(String name) {
        return tagsRepository.findTagByName(name);
    }
    @Transactional
    @Override
    public Tag updateTag(Long id, Tag tag) {
        Tag tag1=tagsRepository.findOne(id);
        if (tag1==null){
            throw new NotFoundException("不存在该类型");
        }
        BeanUtils.copyProperties(tag,tag1);
        return tagsRepository.save(tag1);
    }

    @Override
    public void deleteTag(Long id) {
      tagsRepository.delete(id);
    }

    @Override
    public List<Tag> listTag(String ids) {
        return tagsRepository.findAll(converToList(ids));
    }
    private   List<Long> converToList(String ids){
  List<Long> list=new ArrayList<>();
  if(!"".equals(ids)&&ids!=null){
      String[] idarray=ids.split(",");
          for (int i=0;i<idarray.length;i++){
          list.add(new Long(idarray[i]));
          }
  }
  return list;
    }
}
